package com.telit.communicate.communicate;

import com.telit.communicate.constant.MsgSource;
import com.telit.communicate.constant.SystemName;
import com.telit.communicate.dto.MsgProcessPathDTO;

import java.util.concurrent.ConcurrentHashMap;


/**
 * @author zhouyu
 * @description 消息处理访问路径缓存(外层读写需考虑线程安全问题)
 */
public class MsgProcessPathCache {

    /**
     * 消息处理访问路径缓存
     */
    private static final ConcurrentHashMap<String, ConcurrentHashMap<String, MsgProcessPathDTO>> SYSTEM_PATH_CACHE = new ConcurrentHashMap<>(SystemName.getFields().length);

    /**
     * 添加消息处理访问路径
     *
     * @param msgProcessPathDTO 消息处理路径dto
     * @return 路径是否已存在
     */
    public static boolean addProcessPath(MsgProcessPathDTO msgProcessPathDTO) {
        String systemName = msgProcessPathDTO.getSystemName();
        String msgSource = msgProcessPathDTO.getMsgSource();
        ConcurrentHashMap<String, MsgProcessPathDTO> map = SYSTEM_PATH_CACHE.get(systemName);
        if (map != null && map.get(msgSource) != null) {
            return false;
        }
        ConcurrentHashMap<String, MsgProcessPathDTO> pathCache = new ConcurrentHashMap<>();
        pathCache.put(msgSource, msgProcessPathDTO);
        SYSTEM_PATH_CACHE.put(systemName, pathCache);
        return true;
    }

    /**
     * 根据待分发系统 和 消息来源获取 消息处理访问路径信息
     *
     * @param systemName 待分发系统
     * @param msgSource  消息来源
     * @return 消息处理访问路径信息
     */
    public static MsgProcessPathDTO getProcessPath(SystemName systemName, MsgSource msgSource) {
        ConcurrentHashMap<String, MsgProcessPathDTO> map = SYSTEM_PATH_CACHE.get(systemName.name());
        if (map == null) {
            return null;
        }
        return map.get(msgSource.name());
    }

    /**
     * 根据待分发系统 和 消息来源移除 消息处理访问路径信息
     *
     * @param msgProcessPathDTO 消息处理路径dto
     */
    public static void removeProcessPath(MsgProcessPathDTO msgProcessPathDTO) {
        String systemName = msgProcessPathDTO.getSystemName();
        String msgSource = msgProcessPathDTO.getMsgSource();
        ConcurrentHashMap<String, MsgProcessPathDTO> map = SYSTEM_PATH_CACHE.get(systemName);
        if (map != null) {
            map.remove(msgSource);
        }
    }

}
